import 'package:flutter/material.dart';

class FutureBuilderPage extends StatefulWidget {
  const FutureBuilderPage({super.key});
  @override
  State<FutureBuilderPage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<FutureBuilderPage> {
  Future<String> loadData() async {
    await Future.delayed(const Duration(seconds: 4)); // 等待2秒
    //throw "404 data not found"; // 若需测试异常情况，可把注释去掉
    return "this is server data"; // 正常返回数据
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Title'),
      ),
      body: FutureBuilder(
        future: loadData(), // 读取网络数据，异步函数，返回一个Future类型
        initialData: "我是一个初始值",
        builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
          //测试验证 initalData
          if (snapshot.hasError) {
            return Center(
              child: Text("ERROR: ${snapshot.error}"),
            );
          } else {
            return Center(child: Text("DATA: ${snapshot.data}"));
          }

          // 检查ConnectionState是否为done，以此判断Future是否结束
          /* if (snapshot.connectionState == ConnectionState.done) {
            // 当Future结束时，data和error必有一个不是空
            if (snapshot.hasError) {
              // 判断是否有错误，有则显示错误
              return Center(
                child: Text("ERROR: ${snapshot.error}"),
              );
            } else {
              // 没有错误，则显示数据
              return Center(child: Text("DATA: ${snapshot.data}"));
            }
          } else {
            // Future还没结束，因此渲染一个圆形进度条
            return const Center(
              child: CircularProgressIndicator(),
            );
          }*/
        },
      ),
    );
  }
}
